package com.zjb.utils;

import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Author zhaojianbo
 * @Date 2022/10/18 16:48
 * @Description 尝试匹配密码
 */
public class ExcelUtil {

    /**
     * 获取密码
     *
     * @param excelPath
     * @param fileType    excel文件类型
     * @param tryPassword
     * @return
     * @throws Exception
     */
    public static boolean getExcelPassword(String excelPath, String fileType, String tryPassword) {
        try {
            InputStream inp = new FileInputStream(excelPath);
            if (fileType.equalsIgnoreCase(fileType)) {
                org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword(tryPassword);
                WorkbookFactory.create(inp);
                inp.close();
            } else {
                POIFSFileSystem pfs = new POIFSFileSystem(inp);
                inp.close();
                EncryptionInfo encInfo = new EncryptionInfo(pfs);
                Decryptor decryptor = Decryptor.getInstance(encInfo);
                decryptor.verifyPassword(tryPassword);
                new XSSFWorkbook(decryptor.getDataStream(pfs));
            }
            System.out.println("Password:" + tryPassword);
            return true;
        } catch (Exception e) {
            System.out.println("fail");
            return false;
        }
    }
}
